<?php

namespace app\admin\controller\shopro\commission;

use app\admin\controller\shopro\Common;
use app\admin\model\RechargeCorrectLog;

//自动充正
class RechargeCorrect extends Common
{
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new RechargeCorrectLog();
    }

    /**
     * 查看
     */
    public function index()
    {
        if (!$this->request->isAjax()) {
            $exportConfig = (new \addons\shopro\library\Export())->getConfig();
            $this->assignconfig("save_type", $exportConfig['save_type'] ?? 'download');
            return $this->view->fetch();
        }

        $search=$this->request->param("search");
        $search=json_decode($search,true);
        $where=[];
        if(!empty($search)){
            if(isset($search["createtime"])){
                $time=explode(" - ",$search["createtime"][0]);
                $time0=strtotime($time[0]);
                $time1=strtotime($time[1]);
                $where["a.createtime"]=['between',[$time0,$time1]];
            }
            if(isset($search["user_id"])){
                $where["user_id"]=['=',$search["user_id"][0]];
            }
            if(isset($search["user.nickname"])){
                $where["user_data.nickname"]=['like', '%' .$search["user.nickname"][0]. '%'];
            }
            if(isset($search["user.mobile"])){
                $where["user_data.mobile"]=['like','%' .$search["user.mobile"][0]. '%'];
            }
        }
        $list = $this->model
            ->alias("a")
            ->field("a.*")
            ->with(['user'])
            ->where($where)
            ->join("user user_data","user_data.id=a.user_id","left")
            ->order("createtime desc,id desc")
            ->paginate($this->request->param('list_rows', 10))
            ->each(function ($v){
                $v["createtime"]=date("Y-m-d H:i:s",$v["createtime"])??'';
            });

        $this->success('获取成功', null, $list);
    }
    /**
     * 详情
     *
     * @param  $id
     */
    public function detail($id)
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $detail = $this->model->with([ 'user'])->where('id', $id)->find();
        if (!$detail) {
            $this->error(__('No Results were found'));
        }
        $this->success('详情', null, $detail);
    }

    /**
     * 导出
     * */
    public function export()
    {
        $cellTitles = [
            // 订单表字段
            'id' => 'ID',
            'user.id' => '用户ID',
            'user.nickname' => '用户昵称',
            'user.mobile' => '用户电话',
            'money' => '金额',
            'order_amount' => '充正货款',
            'createtime' => '创建时间',
        ];
        $search=$this->request->param("search");
        $search=json_decode($search,true);
        $where=[];
        if(!empty($search)){
            if(isset($search["createtime"])){
                $time=explode(" - ",$search["createtime"][0]);
                $time0=strtotime($time[0]);
                $time1=strtotime($time[1]);
                $where["a.createtime"]=['between',[$time0,$time1]];
            }
            if(isset($search["user_id"])){
                $where["user_id"]=['=',$search["user_id"][0]];
            }
            if(isset($search["user.nickname"])){
                $where["user_data.nickname"]=['like', '%' .$search["user.nickname"][0]. '%'];
            }
            if(isset($search["user.mobile"])){
                $where["user_data.mobile"]=['like','%' .$search["user.mobile"][0]. '%'];
            }
        }
        // 数据总条数
        $total =  $this->model->alias("a")
            ->field("a.*")
            ->with(['user'])
            ->where($where)
            ->join("user user_data","user_data.id=a.user_id","left")
            ->where($where)->count();
        if ($total <= 0) {
            $this->error('导出数据为空');
        }

        $export = new \addons\shopro\library\Export();
        $params = [
            'file_name' => '自动充正明细列表',
            'cell_titles' => $cellTitles,
            'total' => $total,
            'is_sub_cell' => false,
        ];

        $result = $export->export($params, function ($pages)  use (&$total_order_amount, &$total_pay_fee, &$total_real_pay_fee, &$total_discount_fee, &$total_score_amount, $total,$where) {
            $datas =  $this->model->alias("a")
                ->field("a.*")
                ->with(['user'])
                ->where($where)
                ->join("user user_data","user_data.id=a.user_id","left")
                ->order("createtime desc,id desc")
                ->limit((($pages['page'] - 1) * $pages['list_rows']), $pages['list_rows'])
                ->select();
            $datas = collection($datas);
            $newDatas = [];
            foreach ($datas as &$item) {
                $data = [
                    // 订单表字段
                    'id' => $item['id'],
                    'user.nickname' =>$item["user"]["nickname"]??'',
                    'user.id' =>$item["user"]["id"]??0,
                    'user.mobile' =>"@".$item["user"]["mobile"]??'',
                    'money' =>$item["money"],
                    'order_amount' =>$item["order_amount"],
                    'createtime' =>date("Y-m-d H:i:s",$item["createtime"]),
                ];
                $newDatas[]=$data;
            }
            return $newDatas;
        });

        $this->success('导出成功' . (isset($result['file_path']) && $result['file_path'] ? '，请在服务器: “' . $result['file_path'] . '” 查看' : ''), null, $result);
    }
}
